/**
 * 
 */
package com.taobao.snowsnow.hibernate.dao.impl;

import java.util.List;

import org.hibernate.Query;

import com.taobao.snowsnow.hibernate.dao.ProductDao;
import com.taobao.snowsnow.hibernate.pojo.Product;

/**
 * @author Tux
 *
 * 创建时间: 2011-4-29 上午09:45:11
 */
@SuppressWarnings("unchecked")
public class ProductDaoImpl extends BaseDaoImpl implements ProductDao {
	
	public Product findById(int id) throws Exception {
		return (Product) getHibernateTemplate().get(Product.class, id);
	}
	
	public List<Product> findByName(String name) throws Exception {
		return super.findByProperty(Product.class, "name", name);
	}

	public List<Product> findAll() throws Exception {
		return getHibernateTemplate().find("from Product");
	}

	public long getTotal() throws Exception {
		return super.countByCriteria(Product.class);
	}

	public List<Product> paging(int page, int limit) throws Exception {
		return super.findByCriteriaByPage(Product.class, page, limit);
	}

	@Override
	public Product getFirstObject() throws Exception {
		Query query = getSession().createQuery("from Product as o where o.id = (select min(id) from Product)");
		List<Product> list = query.list();
		if(list.size() !=0)
			return (Product) list.get(0);
		else return null;
	}

	@Override
	public Product getLastObject() throws Exception {
		Query query = getSession().createQuery("from Product as o where o.id = (select max(id) from Product)");
		List<Product> list = query.list();
		if(list.size() !=0)
			return (Product) list.get(0);
		else return null;
	}

	@Override
	public Product findByNamePrecise(String name) throws Exception {
		List<Product> list = findByName(name);
		if(list.size() > 0)
			return list.get(0);
		return null;
	}

	@Override
	public Product findByProduct(Product product) throws Exception {
		Query query = getSession().createQuery("from Product as p where p.color.name=:color and p.dimension.name=:dimension and p.productCollect=:productCollect and p.sellingPrice=:price");
		query.setString("color", product.getColor().getName());
		query.setString("dimension", product.getDimension().getName());
		query.setEntity("productCollect", product.getProductCollect());
		query.setFloat("price", product.getSellingPrice());
		
		List<Product> list = query.list();
		
		if(list.size() > 0)
			return list.get(0);
		return null;
	}
}
